<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->
<template>
    <div class="min-h-screen bg-gray-50">
        <!-- 顶部导航栏 -->
        <Header />
        <!-- 左侧导航栏 -->
        <aside class="fixed left-0 top-16 bottom-0 w-64 bg-gray-800 text-white z-10 overflow-y-auto">
            <nav class="py-4">
                <div v-for="(menu, index) in mainMenus" :key="index" class="mb-1">
                    <div class="flex items-center px-6 py-3 cursor-pointer hover:bg-gray-700"
                        :class="{ 'bg-blue-700': menu.active }" @click="toggleMenu(index)">
                        <i :class="menu.icon + ' mr-3 w-5 text-center'"></i>
                        <span>{{ menu.name }}</span>
                        <i class="fas fa-chevron-down ml-auto text-xs transition-transform duration-200"
                            :class="{ 'transform rotate-180': menu.expanded }"></i>
                    </div>
                    <div v-if="menu.expanded" class="bg-gray-900">
                        <div v-for="(submenu, subIndex) in menu.subMenus" :key="subIndex"
                            class="flex items-center px-10 py-2 cursor-pointer hover:bg-gray-700"
                            :class="{ 'text-blue-400': submenu.active }" @click="selectSubmenu(index, subIndex)">
                            <router-link v-if="menu.name === '监测报警' && submenu.name === '数据汇聚功能'" to="/data-aggregation"
                                @click.native="handleMenuClick" data-readdy="true" class="text-sm">{{ submenu.name
                                }}</router-link>
                            <router-link v-else-if="submenu.link" :to="submenu.link" @click.native="handleMenuClick"
                                data-readdy="true" class="text-sm">{{
                                    submenu.name }}</router-link>
                            <span v-else class="text-sm">{{ submenu.name }}</span>
                        </div>
                    </div>
                </div>
            </nav>
        </aside>
        <!-- 主内容区域 -->
        <main class="pt-16 pl-64">
            <div class="container mx-auto p-6">
                <!-- 面包屑导航 -->
                <div class="flex items-center text-sm mb-6 text-gray-500">
                    <span>首页</span>
                    <i class="fas fa-chevron-right mx-2 text-xs"></i>
                    <span>监测报警</span>
                    <i class="fas fa-chevron-right mx-2 text-xs"></i>
                    <span class="text-blue-600">数据汇聚功能</span>
                </div>
                <!-- 数据概览卡片 -->
                <div class="grid grid-cols-4 gap-6 mb-6">
                    <div v-for="(card, index) in overviewCards" :key="index"
                        class="bg-white rounded-lg shadow-sm p-6 flex items-center">
                        <div class="w-12 h-12 rounded-lg flex items-center justify-center" :class="card.bgColor">
                            <i :class="card.icon + ' text-white text-xl'"></i>
                        </div>
                        <div class="ml-4">
                            <h3 class="text-gray-500 text-sm">{{ card.title }}</h3>
                            <div class="flex items-end mt-1">
                                <span class="text-2xl font-bold">{{ card.value }}</span>
                                <span class="text-xs ml-2"
                                    :class="card.trend === 'up' ? 'text-green-500' : 'text-red-500'">
                                    <i :class="card.trend === 'up' ? 'fas fa-arrow-up' : 'fas fa-arrow-down'"></i>
                                    {{ card.percentage }}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 主要内容区域 -->
                <div class="grid grid-cols-3 gap-6 mb-6">
                    <!-- 区域分布图 -->
                    <div class="bg-white rounded-lg shadow-sm col-span-2 overflow-hidden">
                        <div class="p-4 border-b border-gray-100 flex justify-between items-center">
                            <h2 class="font-bold text-gray-700">区域风险分布</h2>
                            <div class="flex space-x-2">
                                <button
                                    :class="['px-3 py-1 text-sm rounded !rounded-button whitespace-nowrap cursor-pointer',
                                        currentRiskPeriod === 'day' ? 'bg-blue-600 text-white hover:bg-blue-700' : 'bg-gray-100 hover:bg-gray-200']"
                                    @click="changeRiskPeriod('day')">今日</button>
                                <button
                                    :class="['px-3 py-1 text-sm rounded !rounded-button whitespace-nowrap cursor-pointer',
                                        currentRiskPeriod === 'week' ? 'bg-blue-600 text-white hover:bg-blue-700' : 'bg-gray-100 hover:bg-gray-200']"
                                    @click="changeRiskPeriod('week')">本周</button>
                                <button
                                    :class="['px-3 py-1 text-sm rounded !rounded-button whitespace-nowrap cursor-pointer',
                                        currentRiskPeriod === 'month' ? 'bg-blue-600 text-white hover:bg-blue-700' : 'bg-gray-100 hover:bg-gray-200']"
                                    @click="changeRiskPeriod('month')">本月</button>
                            </div>
                        </div>
                        <div class="p-4">
                            <div id="areaRiskMap" class="h-96" ref="areaRiskMap"></div>
                        </div>
                    </div>
                    <!-- 报警事件列表 -->
                    <div class="bg-white rounded-lg shadow-sm">
                        <div class="p-4 border-b border-gray-100 flex justify-between items-center">
                            <h2 class="font-bold text-gray-700">实时报警事件</h2>
                            <router-link to="/alarm-event-management" data-readdy="true"
                                class="text-blue-600 text-sm hover:text-blue-800 !rounded-button whitespace-nowrap cursor-pointer">查看全部</router-link>
                        </div>
                        <div class="p-4 overflow-y-auto h-96">
                            <div v-for="(alarm, index) in alarmEvents" :key="index"
                                class="border-l-4 p-3 mb-3 bg-gray-50 hover:bg-gray-100 cursor-pointer" :class="{
                                    'border-red-500': alarm.level === 1,
                                    'border-orange-500': alarm.level === 2,
                                    'border-yellow-500': alarm.level === 3,
                                    'border-blue-500': alarm.level === 4
                                }">
                                <div class="flex justify-between items-start">
                                    <span class="inline-block px-2 py-1 text-xs rounded-full text-white mb-2" :class="{
                                        'bg-red-500': alarm.level === 1,
                                        'bg-orange-500': alarm.level === 2,
                                        'bg-yellow-500': alarm.level === 3,
                                        'bg-blue-500': alarm.level === 4
                                    }">
                                        {{ alarm.levelText }}
                                    </span>
                                    <span class="text-xs text-gray-500">{{ alarm.time }}</span>
                                </div>
                                <h4 class="font-medium text-gray-800">{{ alarm.title }}</h4>
                                <p class="text-sm text-gray-600 mt-1">{{ alarm.description }}</p>
                                <div class="flex justify-between items-center mt-2">
                                    <span class="text-xs text-gray-500">{{ alarm.location }}</span>
                                    <button @click="scheduleInspection(index)"
                                        class="text-xs text-blue-600 hover:text-blue-800 !rounded-button whitespace-nowrap cursor-pointer">处理</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 统计图表区域 -->
                <div class="grid grid-cols-3 gap-6">
                    <!-- 设备接入率趋势图 -->
                    <div class="bg-white rounded-lg shadow-sm">
                        <div class="p-4 border-b border-gray-100">
                            <h2 class="font-bold text-gray-700">设备接入率趋势</h2>
                        </div>
                        <div class="p-4">
                            <div id="deviceConnectionChart" class="h-64" ref="deviceConnectionChart"></div>
                        </div>
                    </div>
                    <!-- 报警统计分析图 -->
                    <div class="bg-white rounded-lg shadow-sm">
                        <div class="p-4 border-b border-gray-100">
                            <h2 class="font-bold text-gray-700">报警统计分析</h2>
                        </div>
                        <div class="p-4">
                            <div id="alarmAnalysisChart" class="h-64" ref="alarmAnalysisChart"></div>
                        </div>
                    </div>
                    <!-- 在线率分析图 -->
                    <div class="bg-white rounded-lg shadow-sm">
                        <div class="p-4 border-b border-gray-100">
                            <h2 class="font-bold text-gray-700">在线率分析</h2>
                        </div>
                        <div class="p-4">
                            <div id="onlineRateChart" class="h-64" ref="onlineRateChart"></div>
                        </div>
                    </div>
                </div>
                <!-- 视频监控区域 -->
                <div class="mt-6 bg-white rounded-lg shadow-sm">
                        <div class="p-4 border-b border-gray-100 flex justify-between items-center">
                            <h2 class="font-bold text-gray-700">视频监控</h2>
                            <div class="flex space-x-2">
                                <button
                                    :class="['px-3 py-1 text-sm rounded !rounded-button whitespace-nowrap cursor-pointer',
                                        currentVideoFilter === 'all' ? 'bg-blue-600 text-white' : 'bg-gray-100']"
                                    @click="changeVideoFilter('all')">全部</button>
                                <button
                                    :class="['px-3 py-1 text-sm rounded !rounded-button whitespace-nowrap cursor-pointer',
                                        currentVideoFilter === 'key' ? 'bg-blue-600 text-white' : 'bg-gray-100']"
                                    @click="changeVideoFilter('key')">关键区域</button>
                                <button
                                    :class="['px-3 py-1 text-sm rounded !rounded-button whitespace-nowrap cursor-pointer',
                                        currentVideoFilter === 'production' ? 'bg-blue-600 text-white' : 'bg-gray-100']"
                                    @click="changeVideoFilter('production')">生产线</button>
                            </div>
                        </div>
                    <div class="p-4">
                        <div class="grid grid-cols-4 gap-4">
                            <div v-for="(camera, index) in filteredCameras" :key="index"
                                class="relative overflow-hidden rounded-lg">
                                <img :src="camera.image" alt="监控画面" class="w-full h-40 object-cover object-top">
                                <div
                                    class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black to-transparent p-3">
                                    <h4 class="text-white text-sm font-medium">{{ camera.name }}</h4>
                                    <p class="text-gray-300 text-xs">{{ camera.location }}</p>
                                </div>
                                <div
                                    class="absolute top-2 right-2 bg-black bg-opacity-50 text-white text-xs px-2 py-1 rounded">
                                    <i class="fas fa-circle text-green-500 mr-1"></i> 在线
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</template>
<script setup>
import { useRouter } from 'vue-router'
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts';
import chinaMap from "./1.js"
import { ElMessageBox, ElMessage } from 'element-plus'
import Header from '../components/Header.vue';

// 模拟API服务
const mockApiService = {
    // 获取数据概览信息
    async getOverviewData() {
        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 模拟动态数据，每次调用都会有轻微变化
        const baseData = {
            totalDevices: 1286,
            onlineDevices: 1075,
            todayAlarms: 42,
            pendingAlarms: 18
        }
        
        // 添加随机变化来模拟实时数据
        const variation = () => Math.floor(Math.random() * 10) - 5 // -5 到 +5 的随机变化
        
        return {
            totalDevices: baseData.totalDevices + variation(),
            onlineDevices: baseData.onlineDevices + variation(),
            todayAlarms: Math.max(0, baseData.todayAlarms + variation()),
            pendingAlarms: Math.max(0, baseData.pendingAlarms + variation())
        }
    }
}

// 添加区域风险分布筛选状态
const currentRiskPeriod = ref('month')

// 添加视频监控区域筛选状态
const currentVideoFilter = ref('key')

// 添加加载状态
const isLoadingOverview = ref(false)

// 添加视频监控数据
const cameras = ref([
    {
        name: '高炉1号监控',
        location: '炼铁厂 - 高炉区域',
        image: 'https://img.zcool.cn/community/01f9ea5541f8c10000019ae9df6ad4.jpg@1280w_1l_2o_100sh.jpg'
    },
    {
        name: '高炉2号监控',
        location: '炼铁厂 - 高炉区域',
        image: 'https://img.zcool.cn/community/01f9ea5541f8c10000019ae9df6ad4.jpg@1280w_1l_2o_100sh.jpg'
    },
    {
        name: '轧钢机监控',
        location: '轧钢厂 - 主车间',
        image: 'https://img.zcool.cn/community/01f9ea5541f8c10000019ae9df6ad4.jpg@1280w_1l_2o_100sh.jpg'
    },
    {
        name: '连铸机监控',
        location: '连铸车间 - 主区域',
        image: 'https://img.zcool.cn/community/01f9ea5541f8c10000019ae9df6ad4.jpg@1280w_1l_2o_100sh.jpg'
    }
])

// 动态数据获取函数
const fetchOverviewData = async () => {
    try {
        isLoadingOverview.value = true
        const data = await mockApiService.getOverviewData()
        
        // 计算在线率和趋势
        const onlineRate = ((data.onlineDevices / data.totalDevices) * 100).toFixed(1)
        const previousOnlineRate = 83.6 // 模拟之前的在线率
        const onlineRateTrend = parseFloat(onlineRate) > previousOnlineRate ? 'up' : 'down'
        const onlineRateChange = Math.abs(parseFloat(onlineRate) - previousOnlineRate).toFixed(1)
        
        // 更新数据概览卡片
        overviewCards.value = [
            {
                title: '设备接入总数',
                value: data.totalDevices.toLocaleString(),
                percentage: '5.8%',
                trend: 'up',
                icon: 'fas fa-microchip',
                bgColor: 'bg-blue-600'
            },
            {
                title: '当前在线设备',
                value: data.onlineDevices.toLocaleString(),
                percentage: `${onlineRate}%`,
                trend: onlineRateTrend,
                icon: 'fas fa-plug',
                bgColor: 'bg-green-500'
            },
            {
                title: '今日报警次数',
                value: data.todayAlarms.toString(),
                percentage: '12.3%',
                trend: 'down',
                icon: 'fas fa-exclamation-circle',
                bgColor: 'bg-red-500'
            },
            {
                title: '待处理报警',
                value: data.pendingAlarms.toString(),
                percentage: '3.5%',
                trend: data.pendingAlarms > 18 ? 'up' : 'down',
                icon: 'fas fa-tasks',
                bgColor: 'bg-orange-500'
            }
        ]
    } catch (error) {
        // 如果API失败，保持原有静态数据
    } finally {
        isLoadingOverview.value = false
    }
}

// 定时刷新数据
let refreshInterval = null

const startDataRefresh = () => {
    // 立即获取一次数据
    fetchOverviewData()
    
    // 每30秒刷新一次数据
    refreshInterval = setInterval(() => {
        fetchOverviewData()
    }, 30000)
}

const stopDataRefresh = () => {
    if (refreshInterval) {
        clearInterval(refreshInterval)
        refreshInterval = null
    }
}

const handleMenuClick = () => {
    // 延迟执行刷新，确保路由已跳转
    setTimeout(() => {
        window.location.reload();
    }, 100);
};

// 区域风险分布按钮点击功能
const changeRiskPeriod = (period) => {
    currentRiskPeriod.value = period
    updateRiskMap(period)
}

// 更新风险地图数据
const updateRiskMap = (period) => {
    const chart = echarts.getInstanceByDom(areaRiskMap.value)
    if (!chart) return

    // 根据不同时间段更新数据
    let data = []
    if (period === 'day') {
        data = [
            { name: '北京', value: 35 },
            { name: '天津', value: 42 },
            { name: '河北', value: 58 },
            { name: '山西', value: 65 },
            { name: '内蒙古', value: 25 }
        ]
    } else if (period === 'week') {
        data = [
            { name: '北京', value: 40 },
            { name: '天津', value: 52 },
            { name: '河北', value: 68 },
            { name: '山西', value: 75 },
            { name: '内蒙古', value: 30 }
        ]
    } else if (period === 'month') {
        data = [
            { name: '北京', value: 45 },
            { name: '天津', value: 62 },
            { name: '河北', value: 78 },
            { name: '山西', value: 85 },
            { name: '内蒙古', value: 35 },
            { name: '辽宁', value: 68 },
            { name: '吉林', value: 42 },
            { name: '黑龙江', value: 53 },
            { name: '上海', value: 38 },
            { name: '江苏', value: 65 },
            { name: '浙江', value: 48 },
            { name: '安徽', value: 72 },
            { name: '福建', value: 28 },
            { name: '江西', value: 45 },
            { name: '山东', value: 82 },
            { name: '河南', value: 75 },
            { name: '湖北', value: 58 },
            { name: '湖南', value: 52 },
            { name: '广东', value: 35 },
            { name: '广西', value: 42 },
            { name: '海南', value: 25 },
            { name: '重庆', value: 63 },
            { name: '四川', value: 57 },
            { name: '贵州', value: 48 },
            { name: '云南', value: 38 },
            { name: '西藏', value: 15 },
            { name: '陕西', value: 68 },
            { name: '甘肃', value: 55 },
            { name: '青海', value: 28 },
            { name: '宁夏', value: 45 },
            { name: '新疆', value: 35 },
            { name: '台湾', value: 0 },
            { name: '香港', value: 0 },
            { name: '澳门', value: 0 },
            { name: '南海诸岛', value: 0 }
        ]
    }

    // 更新图表数据
    chart.setOption({
        series: [{
            data: data
        }]
    })
}
// 处理报警事件（使用 Element Plus 确认框）
const scheduleInspection = async (index) => {
    try {
        await ElMessageBox.confirm('安排处理该报警事件？', '确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        alarmEvents.value.splice(index, 1)
        ElMessage({ type: 'success', message: '已安排处理并移除该报警' })
    } catch (e) {
        ElMessage({ type: 'info', message: '已取消操作' })
    }
}

// 视频监控区域按钮点击功能
const changeVideoFilter = (filter) => {
    currentVideoFilter.value = filter
    updateCameras()
}

// 根据筛选条件获取摄像头列表
const filteredCameras = ref([])

// 更新摄像头列表
const updateCameras = () => {
    if (currentVideoFilter.value === 'all') {
        filteredCameras.value = [
            {
                name: '3号高炉煤气管道',
                location: '炼铁厂',
                image: 'https://readdy.ai/api/search-image?query=Industrial%20steel%20factory%20interior%20with%20large%20pipes%20and%20machinery%2C%20high%20pressure%20gas%20pipes%20in%20a%20metallurgical%20plant%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment&width=400&height=300&seq=1&orientation=landscape'
            },
            {
                name: '2号轧钢机',
                location: '轧钢厂',
                image: 'https://readdy.ai/api/search-image?query=Steel%20rolling%20mill%20machinery%20in%20operation%2C%20industrial%20equipment%20for%20metal%20processing%2C%20heavy%20machinery%20in%20a%20metallurgical%20plant%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment&width=400&height=300&seq=2&orientation=landscape'
            },
            {
                name: '连铸机冷却水系统',
                location: '连铸车间',
                image: 'https://readdy.ai/api/search-image?query=Continuous%20casting%20machine%20cooling%20water%20system%20in%20a%20steel%20plant%2C%20industrial%20water%20pipes%20and%20cooling%20equipment%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment%20with%20blue%20tinted%20lighting&width=400&height=300&seq=3&orientation=landscape'
            },
            {
                name: '1号除尘器',
                location: '烧结厂',
                image: 'https://readdy.ai/api/search-image?query=Industrial%20dust%20collection%20system%20in%20a%20steel%20sintering%20plant%2C%20large%20filtration%20equipment%2C%20dust%20extraction%20machinery%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment%20with%20slight%20haze&width=400&height=300&seq=4&orientation=landscape'
            },
            {
                name: '主变电站',
                location: '动力厂',
                image: 'https://readdy.ai/api/search-image?query=Industrial%20power%20substation%20in%20a%20steel%20plant%2C%20electrical%20equipment%2C%20transformers%20and%20control%20panels%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment%20with%20warning%20signs&width=400&height=300&seq=5&orientation=landscape'
            },
            {
                name: '原料堆场',
                location: '原料厂',
                image: 'https://readdy.ai/api/search-image?query=Raw%20material%20storage%20yard%20in%20a%20steel%20plant%2C%20piles%20of%20iron%20ore%20and%20coal%2C%20material%20handling%20equipment%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment%20with%20outdoor%20lighting&width=400&height=300&seq=6&orientation=landscape'
            },
            {
                name: '炼钢转炉',
                location: '炼钢厂',
                image: 'https://readdy.ai/api/search-image?query=Steel%20converter%20in%20operation%20with%20molten%20metal%20and%20sparks%2C%20steelmaking%20process%20in%20a%20metallurgical%20plant%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment%20with%20orange%20glow%20from%20hot%20metal&width=400&height=300&seq=7&orientation=landscape'
            },
            {
                name: '成品库',
                location: '成品仓库',
                image: 'https://readdy.ai/api/search-image?query=Finished%20steel%20products%20warehouse%2C%20stacked%20steel%20coils%20and%20plates%2C%20material%20handling%20equipment%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment%20with%20organized%20storage&width=400&height=300&seq=8&orientation=landscape'
            }
        ]
    } else if (currentVideoFilter.value === 'key') {
        filteredCameras.value = [
            {
                name: '连铸机冷却水系统',
                location: '连铸车间',
                image: 'https://readdy.ai/api/search-image?query=Continuous%20casting%20machine%20cooling%20water%20system%20in%20a%20steel%20plant%2C%20industrial%20water%20pipes%20and%20cooling%20equipment%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment%20with%20blue%20tinted%20lighting&width=400&height=300&seq=3&orientation=landscape'
            },
            {
                name: '主变电站',
                location: '动力厂',
                image: 'https://readdy.ai/api/search-image?query=Industrial%20power%20substation%20in%20a%20steel%20plant%2C%20electrical%20equipment%2C%20transformers%20and%20control%20panels%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment%20with%20warning%20signs&width=400&height=300&seq=5&orientation=landscape'
            },
            {
                name: '原料堆场',
                location: '原料厂',
                image: 'https://readdy.ai/api/search-image?query=Raw%20material%20storage%20yard%20in%20a%20steel%20plant%2C%20piles%20of%20iron%20ore%20and%20coal%2C%20material%20handling%20equipment%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment%20with%20outdoor%20lighting&width=400&height=300&seq=6&orientation=landscape'
            },
            {
                name: '成品库',
                location: '成品仓库',
                image: 'https://readdy.ai/api/search-image?query=Finished%20steel%20products%20warehouse%2C%20stacked%20steel%20coils%20and%20plates%2C%20material%20handling%20equipment%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment%20with%20organized%20storage&width=400&height=300&seq=8&orientation=landscape'
            }
        ]
    } else if (currentVideoFilter.value === 'production') {
        filteredCameras.value = [
            {
                name: '3号高炉煤气管道',
                location: '炼铁厂',
                image: 'https://readdy.ai/api/search-image?query=Industrial%20steel%20factory%20interior%20with%20large%20pipes%20and%20machinery%2C%20high%20pressure%20gas%20pipes%20in%20a%20metallurgical%20plant%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment&width=400&height=300&seq=1&orientation=landscape'
            },
            {
                name: '2号轧钢机',
                location: '轧钢厂',
                image: 'https://readdy.ai/api/search-image?query=Steel%20rolling%20mill%20machinery%20in%20operation%2C%20industrial%20equipment%20for%20metal%20processing%2C%20heavy%20machinery%20in%20a%20metallurgical%20plant%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment&width=400&height=300&seq=2&orientation=landscape'
            },
            {
                name: '1号除尘器',
                location: '烧结厂',
                image: 'https://readdy.ai/api/search-image?query=Industrial%20dust%20collection%20system%20in%20a%20steel%20sintering%20plant%2C%20large%20filtration%20equipment%2C%20dust%20extraction%20machinery%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment%20with%20slight%20haze&width=400&height=300&seq=4&orientation=landscape'
            },
            {
                name: '炼钢转炉',
                location: '炼钢厂',
                image: 'https://readdy.ai/api/search-image?query=Steel%20converter%20in%20operation%20with%20molten%20metal%20and%20sparks%2C%20steelmaking%20process%20in%20a%20metallurgical%20plant%2C%20industrial%20monitoring%20camera%20view%2C%20clear%20visibility%2C%20modern%20industrial%20environment%20with%20orange%20glow%20from%20hot%20metal&width=400&height=300&seq=7&orientation=landscape'
            },
        ]
    }
}
const showNotifications = ref(false)
const unreadNotifications = ref([
    {
        id: 1,
        title: '高炉煤气泄漏报警',
        time: '10:23:45',
        description: '3号高炉煤气管道压力异常，可能存在泄漏风险',
        level: 1
    },
    {
        id: 2,
        title: '轧钢机温度过高',
        time: '09:15:32',
        description: '2号轧钢机轴承温度超过阈值，需要立即检查',
        level: 2
    },
    {
        id: 3,
        title: '冷却水系统压力异常',
        time: '08:47:12',
        description: '连铸机冷却水系统压力波动，需要关注',
        level: 3
    }
])
const mainMenus = ref([
    {
        name: '监测报警',
        icon: 'fas fa-bell',
        expanded: true,
        active: true,
        subMenus: [
            { name: '数据汇聚功能', active: true, link: '/data-aggregation' },
            { name: '监测指标统计', active: false, link: '/monitoring-indicators' },
            { name: '区域化展示', active: false, link: '/regional-display' }
        ]
    },
    {
        name: '风险研判',
        icon: 'fas fa-exclamation-triangle',
        expanded: false,
        active: false,
        subMenus: [
            { name: '智能风险评估', active: false, link: '/intelligent-risk-assessment' },
            { name: '预警信息推送', active: false, link: '/risk-warning-push' },
            { name: '风险管理与分析', active: false, link: '/risk-analysis' },
        ]
    },
    {
        name: '在线巡查',
        icon: 'fas fa-search',
        expanded: false,
        active: false,
        subMenus: [
            { name: '企业信息汇总', active: false, link: '/summary-information' },
            { name: '巡查功能', active: false, link: '/patrol' },
            { name: '检索功能', active: false, link: 'search' },
            { name: '一屏汇聚展示', active: false, link: '/screen-display' }
        ]
    },
    {
        name: '综合分析',
        icon: 'fas fa-chart-line',
        expanded: false,
        active: false,
        subMenus: [
            { name: '联网与设备分析', active: false, link: '/equipment' },
            { name: '应用情况分析', active: false, link: '/application' },
            { name: '数据质量分析', active: false, link: '/data-quality' },
            { name: '定期专题报告', active: false, link: 'report' }
        ]
    },
    {
        name: '系统管理',
        icon: 'fas fa-cog',
        expanded: false,
        active: false,
        subMenus: [
            { name: '用户权限管理', active: false, link: 'user-permission' },
            { name: '系统配置管理', active: false, link: 'system-manage' },
            { name: '数据管理', active: false, link: 'data-manage' },
            { name: '系统监控与维护', active: false, link: 'monitoring' }
        ]
    }
])
// 修改原有的静态数据为响应式数据
const overviewCards = ref([
    {
        title: '设备接入总数',
        value: '加载中...',
        percentage: '5.8%',
        trend: 'up',
        icon: 'fas fa-microchip',
        bgColor: 'bg-blue-600'
    },
    {
        title: '当前在线设备',
        value: '加载中...',
        percentage: '83.6%',
        trend: 'up',
        icon: 'fas fa-plug',
        bgColor: 'bg-green-500'
    },
    {
        title: '今日报警次数',
        value: '加载中...',
        percentage: '12.3%',
        trend: 'down',
        icon: 'fas fa-exclamation-circle',
        bgColor: 'bg-red-500'
    },
    {
        title: '待处理报警',
        value: '加载中...',
        percentage: '3.5%',
        trend: 'up',
        icon: 'fas fa-tasks',
        bgColor: 'bg-orange-500'
    }
])
const alarmEvents = ref([
    {
        level: 1,
        levelText: '重大风险',
        time: '10:23:45',
        title: '高炉煤气泄漏报警',
        description: '3号高炉煤气管道压力异常，可能存在泄漏风险',
        location: '炼铁厂 - 3号高炉'
    },
    {
        level: 2,
        levelText: '较大风险',
        time: '09:15:32',
        title: '轧钢机温度过高',
        description: '2号轧钢机轴承温度超过阈值，需要立即检查',
        location: '轧钢厂 - 2号轧钢机'
    },
    {
        level: 3,
        levelText: '一般风险',
        time: '08:47:12',
        title: '冷却水系统压力异常',
        description: '连铸机冷却水系统压力波动，需要关注',
        location: '连铸车间 - 冷却水系统'
    },
    {
        level: 4,
        levelText: '较小风险',
        time: '08:05:56',
        title: '除尘设备效率下降',
        description: '1号除尘器效率下降，建议安排维护检查',
        location: '烧结厂 - 除尘系统'
    },
    {
        level: 2,
        levelText: '较大风险',
        time: '07:38:21',
        title: '变电站电压波动',
        description: '主变电站电压波动较大，可能影响设备稳定运行',
        location: '动力厂 - 主变电站'
    }
])


// 图表引用
const areaRiskMap = ref(null)
const deviceConnectionChart = ref(null)
const alarmAnalysisChart = ref(null)
const onlineRateChart = ref(null)

// 路由实例，用于整块区域点击跳转
const router = useRouter()

// 方法
const toggleNotifications = () => {
    showNotifications.value = !showNotifications.value
}

const markAsRead = (id) => {
    unreadNotifications.value = unreadNotifications.value.filter(notification => notification.id !== id)
}

const markAllAsRead = () => {
    unreadNotifications.value = []
    showNotifications.value = false
}

const viewAllNotifications = () => {
    // 预留查看全部通知的交互逻辑
}

const toggleMenu = (index) => {
    mainMenus.value[index].expanded = !mainMenus.value[index].expanded
    if (mainMenus.value[index].expanded) {
        mainMenus.value.forEach((menu, i) => {
            if (i !== index) {
                menu.expanded = false
            }
        })
    }
}
const selectSubmenu = (menuIndex, submenuIndex) => {
    mainMenus.value.forEach(menu => {
        menu.active = false
        menu.subMenus.forEach(submenu => {
            submenu.active = false
        })
    })
    mainMenus.value[menuIndex].active = true
    mainMenus.value[menuIndex].subMenus[submenuIndex].active = true
    const link = mainMenus.value[menuIndex].subMenus[submenuIndex].link
    if (link) {
        try {
            // 使用路由跳转，确保不论点击文本或整块都能跳转
            const dest = link.startsWith('/') ? link : `/${link}`
            router.push(dest)
        } catch (e) {
            // 回退到浏览器跳转
            window.location.href = link
        }
    }
}
// 图表初始化方法
const initAreaRiskMap = () => {
    if (!areaRiskMap.value) {
        return
    }

    chinaMap(echarts)
    const chart = echarts.init(areaRiskMap.value)
    const option = {
        title: {
            text: '各地区风险指数分布',
            subtext: '实时数据',
            left: 'center',
            top: 10,
            textStyle: {
                color: '#333',
                fontSize: 16,
                fontWeight: 'normal'
            },
            subtextStyle: {
                color: '#666'
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: function (params) {
                return `${params.name}<br/>风险指数: ${params.value}<br/>风险等级: ${params.value >= 80 ? '严重风险' :
                    params.value >= 60 ? '高风险' :
                        params.value >= 40 ? '中等风险' :
                            '低风险'
                    }`;
            }
        },
        visualMap: {
            min: 0,
            max: 100,
            left: 30,
            bottom: 30,
            text: ['高风险', '低风险'],
            inRange: {
                color: ['#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695']
            },
            calculable: true,
            textStyle: {
                color: '#666'
            },
            dimension: 0
        },
        toolbox: {
            show: true,
            right: 30,
            top: 20,
            feature: {
                dataView: { show: true, readOnly: true },
                saveAsImage: { show: true },
            }
        },
        series: [
            {
                name: '风险指数',
                type: 'map',
                map: 'china',
                roam: true,
                zoom: 1.2,
                scaleLimit: {
                    min: 1,
                    max: 3
                },
                label: {
                    show: true,
                    color: '#fff',
                    fontSize: 10
                },
                emphasis: {
                    label: {
                        show: true,
                        color: '#fff',
                        fontSize: 12,
                        fontWeight: 'bold'
                    },
                    itemStyle: {
                        areaColor: '#ff7875'
                    }
                },
                itemStyle: {
                    borderColor: '#fff',
                    borderWidth: 1
                },
                data: [
                    { name: '北京', value: 45 },
                    { name: '天津', value: 62 },
                    { name: '河北', value: 78 },
                    { name: '山西', value: 85 },
                    { name: '内蒙古', value: 35 },
                    { name: '辽宁', value: 68 },
                    { name: '吉林', value: 42 },
                    { name: '黑龙江', value: 53 },
                    { name: '上海', value: 38 },
                    { name: '江苏', value: 65 },
                    { name: '浙江', value: 48 },
                    { name: '安徽', value: 72 },
                    { name: '福建', value: 28 },
                    { name: '江西', value: 45 },
                    { name: '山东', value: 82 },
                    { name: '河南', value: 75 },
                    { name: '湖北', value: 58 },
                    { name: '湖南', value: 52 },
                    { name: '广东', value: 35 },
                    { name: '广西', value: 42 },
                    { name: '海南', value: 25 },
                    { name: '重庆', value: 63 },
                    { name: '四川', value: 57 },
                    { name: '贵州', value: 48 },
                    { name: '云南', value: 38 },
                    { name: '西藏', value: 15 },
                    { name: '陕西', value: 68 },
                    { name: '甘肃', value: 55 },
                    { name: '青海', value: 28 },
                    { name: '宁夏', value: 45 },
                    { name: '新疆', value: 35 }
                ]
            }
        ]
    };
    chart.setOption(option)

    const handleResize = () => chart.resize()
    window.addEventListener('resize', handleResize)

    onUnmounted(() => {
        window.removeEventListener('resize', handleResize)
        chart.dispose()
    })
}
const initDeviceConnectionChart = () => {
    if (!deviceConnectionChart.value) return
    const chart = echarts.init(deviceConnectionChart.value)
    const option = {
        animation: false,
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['接入率', '在线率'],
            right: 10,
            top: 0
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: '{value}%'
            }
        },
        series: [
            {
                name: '接入率',
                type: 'line',
                data: [65, 72, 78, 85, 88, 92, 95],
                smooth: true,
                lineStyle: {
                    width: 3,
                    color: '#4299e1'
                },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            {
                                offset: 0,
                                color: 'rgba(66, 153, 225, 0.5)'
                            },
                            {
                                offset: 1,
                                color: 'rgba(66, 153, 225, 0.05)'
                            }
                        ]
                    }
                }
            },
            {
                name: '在线率',
                type: 'line',
                data: [58, 65, 70, 75, 82, 85, 88],
                smooth: true,
                lineStyle: {
                    width: 3,
                    color: '#48bb78'
                },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            {
                                offset: 0,
                                color: 'rgba(72, 187, 120, 0.5)'
                            },
                            {
                                offset: 1,
                                color: 'rgba(72, 187, 120, 0.05)'
                            }
                        ]
                    }
                }
            }
        ]
    };
    chart.setOption(option);
    // 响应窗口大小变化
    const handleResize = () => chart.resize()
    window.addEventListener('resize', handleResize)
    onUnmounted(() => {
        window.removeEventListener('resize', handleResize)
        chart.dispose()
    })
}

// 生命周期钩子
onMounted(() => {
    initAreaRiskMap()
    initDeviceConnectionChart()
    initAlarmAnalysisChart()
    initOnlineRateChart()
    updateCameras() // 初始化视頻監控數據
    
    // 启动数据刷新
    startDataRefresh()

    // 点击外部关闭通知下拉菜单
    document.addEventListener('click', (e) => {
        const notificationBell = document.getElementById('notificationBell')
        if (notificationBell && !notificationBell.contains(e.target)) {
            showNotifications.value = false
        }
    })
})

// 组件卸载时清理定时器
onUnmounted(() => {
    stopDataRefresh()
})
const initAlarmAnalysisChart = () => {
    if (!alarmAnalysisChart.value) return

    const chart = echarts.init(alarmAnalysisChart.value)
    const option = {
        animation: false,
        tooltip: {
            trigger: 'item'
        },
        legend: {
            orient: 'vertical',
            right: 10,
            top: 'center'
        },
        series: [
            {
                name: '报警类型',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '14',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: [
                    { value: 42, name: '设备故障', itemStyle: { color: '#f56565' } },
                    { value: 28, name: '参数超限', itemStyle: { color: '#ed8936' } },
                    { value: 18, name: '通信异常', itemStyle: { color: '#ecc94b' } },
                    { value: 12, name: '环境异常', itemStyle: { color: '#48bb78' } }
                ]
            }
        ]
    }
    chart.setOption(option)

    const handleResize = () => chart.resize()
    window.addEventListener('resize', handleResize)

    onUnmounted(() => {
        window.removeEventListener('resize', handleResize)
        chart.dispose()
    })
}

const initOnlineRateChart = () => {
    if (!onlineRateChart.value) return

    const chart = echarts.init(onlineRateChart.value)
    const option = {
        animation: false,
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                data: ['炼铁厂', '炼钢厂', '轧钢厂', '烧结厂', '动力厂'],
                axisTick: {
                    alignWithLabel: true
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                axisLabel: {
                    formatter: '{value}%'
                },
                max: 100
            }
        ],
        series: [
            {
                name: '在线率',
                type: 'bar',
                barWidth: '60%',
                data: [
                    {
                        value: 92,
                        itemStyle: {
                            color: '#4299e1'
                        }
                    },
                    {
                        value: 85,
                        itemStyle: {
                            color: '#4299e1'
                        }
                    },
                    {
                        value: 88,
                        itemStyle: {
                            color: '#4299e1'
                        }
                    },
                    {
                        value: 78,
                        itemStyle: {
                            color: '#4299e1'
                        }
                    },
                    {
                        value: 95,
                        itemStyle: {
                            color: '#4299e1'
                        }
                    }
                ]
            }
        ]
    }
    chart.setOption(option)

    const handleResize = () => chart.resize()
    window.addEventListener('resize', handleResize)

    onUnmounted(() => {
        window.removeEventListener('resize', handleResize)
        chart.dispose()
    })
}
</script>
<style scoped>
/* 自定义样式 */
.monitoring__chart-container {
    position: relative;
    width: 100%;
    height: 100%;
}

/* 通知下拉菜单动画 */
.notification-dropdown-enter-active,
.notification-dropdown-leave-active {
    transition: all 0.3s ease;
}

.notification-dropdown-enter,
.notification-dropdown-leave-to {
    transform: translateY(-10px);
    opacity: 0;
}

/* 隐藏input number的箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

input[type="number"] {
    -moz-appearance: textfield;
}
</style>